# -*- coding: utf-8 -*-
import http.server
import socketserver
import os
import webbrowser
import threading
import time
import urllib.parse

# 定义端口
PORT = 8000

# 设置静态文件目录
class CustomHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        # URL解码
        self.path = urllib.parse.unquote(self.path)
        
        # 默认页面
        if self.path == '/':
            self.path = '/templates/index.html'
        # 其他页面路由
        elif self.path == '/character_network':
            self.path = '/templates/character_network.html'
        elif self.path == '/word_frequency':
            self.path = '/templates/word_frequency.html'
        elif self.path == '/topic_evolution':
            self.path = '/templates/topic_evolution.html'
        elif self.path == '/sentiment_analysis':
            self.path = '/templates/sentiment_analysis.html'
        elif self.path == '/qa':
            self.path = '/templates/qa.html'
        elif self.path == '/generation':
            self.path = '/templates/generation.html'
        
        # 确保路径安全
        if '..' in self.path:
            self.send_error(404, "File not found")
            return
            
        # 提供文件
        return http.server.SimpleHTTPRequestHandler.do_GET(self)

def start_server():
    # 获取当前目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 切换到项目根目录
    os.chdir(current_dir)
    
    # 创建服务器
    with socketserver.TCPServer(("", PORT), CustomHandler) as httpd:
        print(f"服务器启动在 http://localhost:{PORT}")
        print("按 Ctrl+C 停止服务器")
        
        # 在新线程中启动浏览器
        def open_browser():
            time.sleep(1)  # 等待服务器启动
            webbrowser.open(f'http://localhost:{PORT}')
        
        threading.Thread(target=open_browser, daemon=True).start()
        
        try:
            # 启动服务器
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\n服务器已停止")
        except Exception as e:
            print(f"\n服务器错误: {e}")

if __name__ == "__main__":
    start_server()